import Snake from './Snake';
import Score from './Score';
import Food from './Food';

/**
 * 控制其他类
 */
class GameControl {
    snake: Snake | null;
    food: Food | null;
    score: Score | null;
    step: number = 0;
    // 存储蛇的移动方向
    direction: string = 'ArrowRight';

    isGameOver: boolean = false;

    constructor() {
        this.snake = new Snake();
        this.food = new Food();
        this.score = new Score(10, 2);
    }

    // 游戏初始化
    init() {
        document.addEventListener('keydown', this.keydownHandler.bind(this));
        this.stepChange();
        this.food!.changeXY();
    }

    // 游戏摧毁
    destroy() {}

    // 创建键盘响应函数
    keydownHandler(event: KeyboardEvent) {
        this.direction = event.key;
    }

    stepChange() {
        let X = this.snake!.X;
        let Y = this.snake!.Y;
        console.log(this.direction);

        // ArrowUp
        // ArrowDown
        switch (this.direction) {
            case 'ArrowUp':
            case 'Up':
                Y -= 10;
                break;
            case 'ArrowDown':
            case 'Down':
                Y += 10;
                break;
            case 'ArrowLeft':
            case 'Left':
                X -= 10;
                break;
            case 'ArrowRight':
            case 'Right':
                X += 10;
                break;
            default:
                break;
        }

        this.checkEat(X, Y);

        try {
            this.snake!.X = X;
            this.snake!.Y = Y;
        } catch (e: any) {
            this.isGameOver = true;
            alert(e.message);
        }

        !this.isGameOver && setTimeout(this.stepChange.bind(this), 300 - this.score!.level * 30 - 30);
    }

    // 检查蛇是否吃到食物
    checkEat(x: number, y: number): boolean {
        let X = this.food?.X;
        let Y = this.food?.Y;

        console.log(X, Y, '--------------', x, y);

        if (x === X && y === Y) {
            console.log('吃到食物了');
            this.snake?.addBody();
            this.food!.changeXY();
            this.score?.addScore();
            return true;
        }

        return false;
    }
}

export default GameControl;
